package com.teaching.service.impl;

import com.teaching.service.TeacherEfficiencyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 教师教学效率服务实现类
 */
@Service
public class TeacherEfficiencyServiceImpl implements TeacherEfficiencyService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 获取教师教学效率数据
     * @param department 教研组/学科
     * @param period 时间周期(week/month/semester/year)
     * @return 教师效率统计数据
     */
    @Override
    public Map<String, Object> getTeacherEfficiencyData(String department, String period) {
        System.out.println("调用getTeacherEfficiencyData方法 - 参数: department=" + department + ", period=" + period);
        
        // 获取日期范围
        LocalDate endDate = LocalDate.now();
        LocalDate startDate;
        
        switch (period) {
            case "week":
                startDate = endDate.minusWeeks(1);
                break;
            case "month":
                startDate = endDate.minusMonths(1);
                break;
            case "semester":
                // 假设一个学期约4个月
                startDate = endDate.minusMonths(4);
                break;
            case "year":
                startDate = endDate.minusYears(1);
                break;
            default:
                startDate = endDate.minusMonths(1); // 默认为一个月
        }
        
        // 格式化日期
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String startDateStr = startDate.format(formatter);
        String endDateStr = endDate.format(formatter);
        
        System.out.println("查询日期范围: " + startDateStr + " 至 " + endDateStr);
        
        // 根据ai_teaching.sql中的表结构调整查询
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT m.id, m.teacher_id, t.name as teacher_name, m.subject as department, ");
        sql.append("m.record_date, ");
        sql.append("m.prep_time as prepTime, m.modification_time as modificationTime, ");
        sql.append("m.exercise_design_time as exerciseDesignTime, m.exercise_modification_time as exerciseModificationTime, ");
        sql.append("m.efficiency_index as efficiency, m.optimization_focus as optimizationFocus, m.improvement_suggestion ");
        sql.append("FROM teaching_efficiency_metrics m ");
        sql.append("JOIN teachers t ON m.teacher_id = t.id ");
        
        // 由于这是测试环境，我们暂时不使用日期过滤，以便获取更多数据
        sql.append("WHERE 1=1 ");
        
        List<Object> params = new ArrayList<>();
        
        // 添加学科筛选条件
        if (department != null && !department.equals("all")) {
            sql.append("AND m.subject = ? ");
            params.add(department);
        }
        
        sql.append("ORDER BY m.record_date DESC");
        
        // 打印SQL和参数
        System.out.println("执行SQL: " + sql.toString());
        System.out.println("SQL参数: " + params);
        
        // 执行查询获取教师效率数据
        List<Map<String, Object>> efficiencyData = new ArrayList<>();
        try {
            efficiencyData = jdbcTemplate.queryForList(
                    sql.toString(), params.toArray());
            System.out.println("查询结果条数: " + efficiencyData.size());
            if (efficiencyData.size() > 0) {
                System.out.println("第一条记录: " + efficiencyData.get(0));
                
                // 处理数据，确保字段名与前端期望的一致
                efficiencyData = efficiencyData.stream().map(record -> {
                    Map<String, Object> newRecord = new HashMap<>(record);
                    return newRecord;
                }).collect(Collectors.toList());
            }
        } catch (Exception e) {
            System.out.println("查询教师效率数据失败: " + e.getMessage());
            e.printStackTrace();
        }
        
        // 统计优化方向分布
        List<Map<String, Object>> optimizationFocus = getOptimizationFocusDistribution(efficiencyData);
        System.out.println("优化方向分布: " + optimizationFocus);
        
        // 获取效率趋势数据
        Map<String, List<Double>> efficiencyTrends = getEfficiencyTrends(department);
        System.out.println("效率趋势数据: " + efficiencyTrends);
        
        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("efficiencyData", efficiencyData);
        result.put("optimizationFocus", optimizationFocus);
        result.put("efficiencyTrends", efficiencyTrends);
        
        System.out.println("返回数据大小: efficiencyData=" + efficiencyData.size() + 
                ", optimizationFocus=" + optimizationFocus.size() + 
                ", efficiencyTrends键数=" + efficiencyTrends.size());
        
        return result;
    }
    
    /**
     * 获取优化方向分布统计
     * @param efficiencyData 效率数据
     * @return 优化方向分布
     */
    private List<Map<String, Object>> getOptimizationFocusDistribution(List<Map<String, Object>> efficiencyData) {
        // 统计各优化方向的出现次数
        Map<String, Long> focusCount = new HashMap<>();
        
        try {
            focusCount = efficiencyData.stream()
                    .filter(item -> item.get("optimizationFocus") != null)
                    .collect(Collectors.groupingBy(
                            item -> (String) item.get("optimizationFocus"),
                            Collectors.counting()
                    ));
            System.out.println("优化方向统计: " + focusCount);
        } catch (Exception e) {
            System.out.println("计算优化方向分布失败: " + e.getMessage());
            e.printStackTrace();
        }
        
        // 转换为前端需要的格式
        List<Map<String, Object>> result = new ArrayList<>();
        try {
            result = focusCount.entrySet().stream()
                    .map(entry -> {
                        Map<String, Object> item = new HashMap<>();
                        item.put("name", entry.getKey());
                        item.put("value", entry.getValue());
                        return item;
                    })
                    .collect(Collectors.toList());
        } catch (Exception e) {
            System.out.println("转换优化方向分布数据失败: " + e.getMessage());
            e.printStackTrace();
        }
        
        return result;
    }
    
    /**
     * 获取效率趋势数据
     * @param department 教研组/学科
     * @return 效率趋势数据
     */
    private Map<String, List<Double>> getEfficiencyTrends(String department) {
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT t.name as teacher_name, m.record_date, m.efficiency_index ");
        sql.append("FROM teaching_efficiency_metrics m ");
        sql.append("JOIN teachers t ON m.teacher_id = t.id ");
        sql.append("WHERE 1=1 ");  // 不使用日期过滤
        
        List<Object> params = new ArrayList<>();
        
        if (department != null && !department.equals("all")) {
            sql.append("AND m.subject = ? ");
            params.add(department);
        }
        
        sql.append("ORDER BY m.teacher_id, m.record_date ASC");
        
        // 打印趋势查询SQL
        System.out.println("趋势查询SQL: " + sql.toString());
        System.out.println("趋势查询参数: " + params);
        
        List<Map<String, Object>> trendData = new ArrayList<>();
        try {
            trendData = jdbcTemplate.queryForList(
                    sql.toString(), params.toArray());
            System.out.println("趋势查询结果条数: " + trendData.size());
            if (trendData.size() > 0) {
                System.out.println("趋势第一条记录: " + trendData.get(0));
            }
        } catch (Exception e) {
            System.out.println("查询效率趋势数据失败: " + e.getMessage());
            e.printStackTrace();
        }
        
        // 按教师分组，获取每个教师的效率趋势
        Map<String, List<Double>> result = new HashMap<>();
        
        try {
            for (Map<String, Object> record : trendData) {
                String teacherName = (String) record.get("teacher_name");
                Object efficiencyObj = record.get("efficiency_index");
                
                if (teacherName == null || efficiencyObj == null) {
                    System.out.println("跳过无效数据: " + record);
                    continue;
                }
                
                Double efficiency = ((Number) efficiencyObj).doubleValue();
                
                if (!result.containsKey(teacherName)) {
                    result.put(teacherName, new ArrayList<>());
                }
                
                result.get(teacherName).add(efficiency);
            }
            
            System.out.println("教师趋势统计: " + result);
        } catch (Exception e) {
            System.out.println("处理效率趋势数据失败: " + e.getMessage());
            e.printStackTrace();
        }
        
        // 最多返回5个教师的数据，避免图表过于拥挤
        if (result.size() > 5) {
            Map<String, List<Double>> limitedResult = new HashMap<>();
            int count = 0;
            
            for (Map.Entry<String, List<Double>> entry : result.entrySet()) {
                if (count >= 5) break;
                limitedResult.put(entry.getKey(), entry.getValue());
                count++;
            }
            
            return limitedResult;
        }
        
        return result;
    }
} 